﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace JieBooLaw.WebAdmin
{
    using JieBooLaw.Common.Web.Util;
    using JieBooLaw.Common.Web;
    using JieBooLaw.Domain;
    using JieBooLaw.Service;
    using Ext.Net;
    using JieBooLaw.Common.Util;
    using JieBooLaw.Common.Security;

    public partial class UserManager : BaseWebPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                this.BindData();
            }
        }

        protected void MyData_Refresh(object sender, StoreRefreshDataEventArgs e)
        {
            this.BindData();
        }

        private void BindData()
        {
            var store = this.GridPanel1.GetStore();

            store.DataSource = GetAllEntity();
            store.DataBind();
        }

        private IList<TSys_User> GetAllEntity()
        {
            TSys_UserSvc svc = new TSys_UserSvc();
            IList<TSys_User> list = svc.GetAllList();

            return list;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            TSys_User user = new TSys_User()
            {
                Account = txtAccount.Text,
                Active = txtActive.Checked,
                Description = txtDescription.Text,
                eMail = txteMail.Text,
                Mobile = txtMobile.Text,
                Password = txtPassword.Text,
                RealName = txtRealName.Text,
                UserID = !string.IsNullOrEmpty(txtUserID.Text) ? 0 : ConvertUtil.ToInt(txtUserID.Text)
            };

            user.Password = Cryptographer.EncryptorAESToString(user.Password);
            if (txtLastLoginTime.SelectedValue != null)
                user.LastLoginTime = ConvertUtil.ToDateTime(txtLastLoginTime.Text);


            TSys_UserSvc svc = new TSys_UserSvc();

            if (string.IsNullOrEmpty(txtUserID.Text))
                svc.Add(user);
            else
                svc.Save(user);

            this.BindData();
            winDetails.Hide();
        }

        protected void btnDelete_Click(object sender, DirectEventArgs e)
        {
            TSys_UserSvc svc = new TSys_UserSvc();

            string json = e.ExtraParams["Values"];

            Dictionary<string, string>[] companies = JSON.Deserialize<Dictionary<string, string>[]>(json);

            foreach (Dictionary<string, string> row in companies)
            {
                string id = row["UserID"];
                string account = row["Account"];
                if (account != "administrator")
                {
                    svc.Delete(new TSys_User() { UserID = ConvertUtil.ToInt(id) });
                }
            }

            this.BindData();
        }
    }
}
